package com.dhecp.project.storage.controller;

import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.shiro.authz.annotation.Logical;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import com.dhecp.common.annotation.Log;
import com.dhecp.common.annotation.RepeatSubmit;
import com.dhecp.common.core.domain.AjaxResult;
import com.dhecp.common.core.page.TableDataInfo;
import com.dhecp.common.enums.BusinessType;
import com.dhecp.common.utils.TypeUtils;
import com.dhecp.core.constant.ModuleTable;
import com.dhecp.core.layui.GridColumnsPropertyModel;
import com.dhecp.core.utils.ExportExcelUtils;
import com.dhecp.framework.util.ShiroUtils;
import com.dhecp.project.business.domain.FbaProductActive;
import com.dhecp.project.business.domain.ProductActive;
import com.dhecp.project.common.controller.BaseModuleController;
import com.dhecp.project.common.domain.ModuleNidAndBid;
import com.dhecp.project.common.service.ModuleNidAndBidService;
import com.dhecp.project.storage.domain.DeliveryRequest;
import com.dhecp.project.storage.domain.DeliveryRequestDetail;
import com.dhecp.project.storage.domain.GaugeMaintenance;
import com.dhecp.project.storage.enums.DeliveryRequestEnum;
import com.dhecp.project.storage.service.DeliveryRequestService;
import com.dhecp.project.system.domain.SysDictionaryForExport;
import com.dhecp.project.system.service.SysDictionaryForFieldService;

/**
 * @program: kjecp
 * @description: 海外仓 控制层
 */
@Controller
@RequestMapping("/storage/deliveryRequest")
public class HWDeliveryRequestController extends BaseModuleController {

    private String prefix = "storage/deliveryRequest";
    private String moduleTable = ModuleTable.DELIVERY_REQUEST;
    private String moduleTable2 = ModuleTable.DELIVERY_REQUEST_DETAIL;
    private String moduleTable3 = ModuleTable.GAUGE_MAINTENANCE;
    private String moduleTable4 = ModuleTable.STOCK_CONTROL;

    @Autowired
    private DeliveryRequestService deliveryRequestService;
    @Autowired
    private GridColumnsPropertyModel gridColumnsPropertyModel;
    @Autowired
    private ModuleNidAndBidService moduleNidAndBidService;
    @Autowired
    private SysDictionaryForFieldService sysDictionaryForFieldService;

    /**
     * @Description: 打开查询列表页
     */
    @RequiresPermissions("storage:deliveryRequest:view")
    @GetMapping()
    public ModelAndView view(@RequestParam Map<String, Object> params) {
        params.put("moduleTable", moduleTable);
        params.put("entity", new DeliveryRequest()); //生成表格gridColumns对应的实体，用于获取实体属性生成表格字段
        params.put("prefix", prefix + "/deliveryRequest"); //页面路径
        params.put("toolBarWidth", 0);
        params.put("checkBox", "yes");
        ModelAndView mv = this.openListPage(params);
        mv.addObject("storage", "deliveryRequest");
        return mv;
    }

    /**
     * @Description: 查询页 列表数据
     */
    @RequiresPermissions("storage:deliveryRequest:list")
    @GetMapping("/list")
    @ResponseBody
    public TableDataInfo list(@RequestParam Map<String, Object> params) {
        params.put("moduleTable", moduleTable);
        List<DeliveryRequest> list = new ArrayList<DeliveryRequest>();
        try {
            params.put("stateName",DeliveryRequestEnum.StateName.SUCCESS.value);
            list = deliveryRequestService.queryList(params);
        } catch (Exception e) {
            e.printStackTrace();
            return getDataTable(this.getExceptionMessage(e).toString());
        }
        return getDataTable(list);
    }

    /**
     * @Description: 查询页 子列表数据
     */
    @RequiresPermissions("storage:deliveryRequest:list")
    @GetMapping("/sonlist")
    @ResponseBody
    public AjaxResult sonlist(@RequestParam Map<String, Object> params) {
        try {

            params.put("moduleTable", moduleTable2);
            params.put("entity", new DeliveryRequestDetail()); //生成表格gridColumns对应的实体，用于获取实体属性生成表格字段
            params.put("toolBarWidth", 0);
            Map<String, Object> dictionaryForFieldMap = new HashMap<String, Object>();
            Map<String, Object> mapList = new HashMap<>();
            mapList.put("sonList", deliveryRequestService.querySonListByBid(params));
            mapList.put("fields", TypeUtils.mapToJson(dictionaryForFieldMap));
            mapList.put("gridColumns", gridColumnsPropertyModel.queryGridColumnsPropertyModel(params));
            AjaxResult ajaxResult = AjaxResult.success(mapList);
            return ajaxResult;
        } catch (Exception e) {
            return AjaxResult.error(this.getExceptionMessage(e));
        }
    }


    /**
     * @Description: 打开制单页
     * @Param: nid 必要参数：单据编码（新增时传默认值 0 ，修改、查看时传单据实际值）
     * @return: org.springframework.web.servlet.ModelAndView
     */
    @RequiresPermissions("storage:deliveryRequest:view")
    @GetMapping("/edit")
    public ModelAndView editPage(@RequestParam Map<String, Object> params) {
        if (params.get("nid") == null || params.get("nid") == "") {
            params.put("nid", "0");
        }
        params.put("moduleTable", moduleTable);
        params.put("entity", new DeliveryRequest()); //用于获取实体属性名取代对应字典字段名，解决大小写敏感问题
        params.put("moduleUrl", prefix); //页面上级路径
        params.put("prefix", prefix + "/deliveryRequest_edit"); //页面路径
        Subject userSubject = ShiroUtils.getSubject();
        int enableEdit = 0;
        boolean vType = false;
        if (params.get(enableEdit) == null || "1".equals(params.get(enableEdit).toString())) {
            if (userSubject.isPermitted("storage:deliveryRequest:edit")) { //当前登录用户主体是否有修改的权限
                enableEdit = 1;
            }
        }

        try {
            Map<String, Object> headData = new HashMap<String, Object>();        //表头的业务数据
            DeliveryRequest businessData = deliveryRequestService.queryFirstRecord(params);
            if (businessData == null) { //未查询到对应单据，页面初始化值
                ModuleNidAndBid moduleNidAndBid = moduleNidAndBidService.queryModuleNidAndBidInitial(params);
                DeliveryRequest deliveryRequest = new DeliveryRequest();
                deliveryRequest.setNid("0");
                deliveryRequest.setBid(moduleNidAndBid.getBid());
                deliveryRequest.setCreateTime(new Date());
                deliveryRequest.setCid(ShiroUtils.getMandatorCid());
                deliveryRequest.setbUser(ShiroUtils.getMandatorId());
                deliveryRequest.setbUserName(ShiroUtils.getMandatorName());
                deliveryRequest.setbDept(ShiroUtils.getMandatorDeptPath());
                deliveryRequest.setbDeptName(ShiroUtils.getMandatorDeptName());
                deliveryRequest.setbPosition(ShiroUtils.getMandatorPositionNameDa());
                deliveryRequest.setaUser(ShiroUtils.getUserId());
                deliveryRequest.setaUserName(ShiroUtils.getUserName());
                deliveryRequest.setaDept(ShiroUtils.getUserDeptPath());
                deliveryRequest.setaDeptName(ShiroUtils.getUserDeptName());
                deliveryRequest.setaPosition(ShiroUtils.getUserPositionNameDa());
                deliveryRequest.setCode(moduleNidAndBid.getBid());
                deliveryRequest.setCid(ShiroUtils.getMandatorCid());
                deliveryRequest.setCidName(ShiroUtils.getMandatorCidName());

                headData = TypeUtils.entityToMap(deliveryRequest);
            } else {
                headData = TypeUtils.entityToMap(businessData);
                vType = businessData.getEffectStock();
            }
            params.put("headData", headData); //表头的业务数据

            params.put("checkBox", "yes"); //生成表格gridColumns时包含复选
            ModelAndView mv = this.openEditPage(params);

            mv.addObject("enableEdit", vType ? 0 : enableEdit); //当前页面是否可编辑（0：不可编辑，1：可编辑）
            if (businessData != null) {
                Map<String, Object> params2 = new HashMap<String, Object>();
                params2.put("moduleTable", moduleTable);
                params2.put("nid", businessData.getNid());
                params2.put("bid", businessData.getBid());
                mv.addObject("detailList", deliveryRequestService.queryDetailListByBid(params2));//明细数据
                mv.addObject("bid", businessData.getBid());//单号
                mv.addObject("warehouseAddress", businessData.getWarehouseAddress());//所在仓库
                mv.addObject("destHouseAddress", businessData.getDestHouseAddress());//目的地仓库
            }
            return mv;
        } catch (Exception e) {
            return this.gotoModelAndViewErrorPage(e.getMessage());    //详细信息
        }
    }


    /**
     * 箱规维护页面
     * @param params
     * @return ModelAndView
     * @author DH-Xxj
     */
    @GetMapping("/select2")
    public ModelAndView selectPurchaseList(@RequestParam Map<String, Object> params) {
        params.put("moduleTable", moduleTable2);
        params.put("entity", new GaugeMaintenance()); //生成表格gridColumns对应的实体，用于获取实体属性生成表格字段
        params.put("toolBarWidth", 0);
        if (params.get("pagetype") != null && params.get("pagetype").toString().equalsIgnoreCase("checkbox"))
            params.put("checkBox", "yes");
        else params.put("radio", "yes");
        ModelAndView mv = this.getModelAndView();
        AjaxResult ajaxResult = new AjaxResult();
        Map<String, Object> dictionaryForFieldMap = new HashMap<String, Object>();
        mv.addObject("fields", TypeUtils.mapToJson(dictionaryForFieldMap));
        mv.addObject("ajaxResult", ajaxResult);
        mv.addObject("gridColumns", gridColumnsPropertyModel.queryGridColumnsPropertyModel(params));
        mv.addObject("prefix", prefix);
        mv.addObject("moduleTable", moduleTable2);
        mv.addObject("pagetype", params.get("pagetype").toString());
        //mv.addObject("fmoduleTable", moduleTable3);//HW_DELIVERYREQUEST_GUAGE
        mv.addObject("fmoduleTable", "HW_DELIVERYREQUEST_GUAGE");
        if (params.get("selectedObject") != null && params.get("selectedObject") != "") {
            String warehouseAddress = params.get("selectedObject").toString();
            mv.addObject("warehouseAddress", warehouseAddress);
        }
        //mv.setViewName("common/select");
        mv.setViewName("system/organization/mzjobject_select");
        return mv;
    }

    /**
     * 打库位编码选择页面
     * @param params
     * @return ModelAndView
     * @author DH-Xxj
     */
    @GetMapping("/getCodeStockLocation")
    public ModelAndView getCodeStockLocation(@RequestParam Map<String, Object> params) {
        params.put("moduleTable", moduleTable4);
        params.put("entity", new ProductActive()); //生成表格gridColumns对应的实体，用于获取实体属性生成表格字段
        params.put("toolBarWidth", 0);
        if (params.get("pagetype") != null && params.get("pagetype").toString().equalsIgnoreCase("checkbox"))
            params.put("checkBox", "yes");
        else params.put("radio", "yes");
        ModelAndView mv = this.getModelAndView();
        AjaxResult ajaxResult = new AjaxResult();
        Map<String, Object> dictionaryForFieldMap = new HashMap<String, Object>();
        mv.addObject("fields", TypeUtils.mapToJson(dictionaryForFieldMap));
        mv.addObject("ajaxResult", ajaxResult);
        mv.addObject("gridColumns", gridColumnsPropertyModel.queryGridColumnsPropertyModel(params));
        mv.addObject("prefix", prefix);
        mv.addObject("moduleTable", "HW_DELIVERYREQUEST_LOCATION");//HW_DELIVERYREQUEST_LOCATION
        mv.addObject("fmoduleTable", "HW_DELIVERYREQUEST_LOCATION");
        mv.addObject("pagetype", params.get("pagetype").toString());
        mv.addObject("warehouseAddress", params.get("warehouseAddress"));
        mv.addObject("vGsBm", params.get("vGsBm"));
        mv.addObject("productcode", params.get("productcode"));
        mv.addObject("noChooseList", params.get("noChooseList"));
        mv.setViewName("common/select");
        return mv;
    }

    /**
     * 查询库存编码
     */
    @GetMapping("/findFbaProductByDeliveryRequestDetail")
    @ResponseBody
    public TableDataInfo findFbaProductByDeliveryRequestDetail(@RequestParam Map<String, Object> params) {
        params.put("moduleTable", moduleTable);
        try {
            String noChooseList = params.get("noChooseList")!=null ? params.get("noChooseList").toString():"";
            if(!noChooseList.equals("")){
                List<String> noChoose = new ArrayList<>();
                String[] noChooseStr = noChooseList.split(",");
                for(int i=0;i<noChooseStr.length;i++){
                    noChoose.add(noChooseStr[i]);
                }
                params.put("noChoose",noChoose);
            }
            List<FbaProductActive> list = deliveryRequestService.findFbaProductByDeliveryRequestDetail(params);
            return getDataTable(list);
        } catch (Exception e) {
            e.printStackTrace();
            return getDataTable(this.getExceptionMessage(e).toString());
        }
    }


    /**
     * 查询箱规维护
     */
    @GetMapping("/selectGuageByStore")
    @ResponseBody
    public TableDataInfo selectGuageByStore(@RequestParam Map<String, Object> params) {
        params.put("moduleTable", moduleTable3);
        try {
            List<DeliveryRequestDetail> list = deliveryRequestService.selectGuageByStore(params);
            return getDataTable(list);
        } catch (Exception e) {
            e.printStackTrace();
            return getDataTable(this.getExceptionMessage(e).toString());
        }
    }

    /**
     * @Description: 保存数据
     * @Param: infoMap 必要参数：非网格字段（包括头部、底部所有显示和隐藏的字段）
     * @Param: infoItems 必要参数：对应实体类的json格式字符串
     * @return: com.dhecp.common.core.domain.AjaxResult
     * @Author: hlf
     * @date: 2022-08-15 15:44
     */
    @RequiresPermissions(value = {"storage:deliveryRequest:add", "storage:deliveryRequest:edit", "storage:deliveryRequest:delete"}, logical = Logical.OR)
    @Log(title = "海外仓发货申请单", businessType = BusinessType.UPDATE)
    @PostMapping("/editpost")
    @ResponseBody
    @RepeatSubmit
    public AjaxResult editpost(@RequestParam Map<String, Object> params) {
        params.put("moduleTable", moduleTable);
        AjaxResult ajaxResult = new AjaxResult();
        try {
            //System.out.println("params"+params);
            ajaxResult = deliveryRequestService.saveData(params);
        } catch (Exception e) {
            e.printStackTrace();
            ajaxResult = AjaxResult.error(this.getExceptionMessage(e));
        }
        return ajaxResult;
    }



    /**
     *@Description: 查询前一单NID、BID
     *@Param: [params] nid 必要参数：当前 单据编码
     *@return: com.dhecp.common.core.domain.AjaxResult (data.nid 前一单NID， data.bid 前一单BID)
     *@Author: hlf
     *@date: 2022-05-09 11:40
     */
    @RequiresPermissions("storage:deliveryRequest:view")
    @GetMapping("/lastnid")
    @ResponseBody
    public AjaxResult lastNid(@RequestParam Map<String, Object> params){
        params.put("moduleTable", moduleTable);
        AjaxResult ajaxResult = new AjaxResult();
        try {
            ajaxResult = deliveryRequestService.queryLastNid(params);
        }catch (Exception e) {
            ajaxResult = AjaxResult.error(this.getExceptionMessage(e));
        }
        return ajaxResult;
    }

    /**
     *@Description: 查询后一单NID、BID
     *@Param: [params] nid 必要参数：当前 单据编码
     *@return: com.dhecp.common.core.domain.AjaxResult (data.nid 后一单NID， data.bid 后一单BID)
     *@Author: hlf
     *@date: 2022-05-09 11:40
     */
    @RequiresPermissions("storage:deliveryRequest:view")
    @GetMapping("/nextnid")
    @ResponseBody
    public AjaxResult nextNid(@RequestParam Map<String, Object> params){
        params.put("moduleTable", moduleTable);
        AjaxResult ajaxResult = new AjaxResult();
        try {
            ajaxResult = deliveryRequestService.queryNextNid(params);
        }catch (Exception e) {
            ajaxResult = AjaxResult.error(this.getExceptionMessage(e));
        }
        return ajaxResult;
    }


    /**
     * @Description: 修改审核状态
     * @Param: [params]
     * @return: com.dhecp.common.core.domain.AjaxResult
     * @Author: hlf
     * @date: 2022-08-17 14:55
     */
    //@RequiresPermissions("storage:deliveryRequest:updateState")
    @Log(title = "修改海外仓发货申请审核状态", businessType = BusinessType.UPDATE)
    @PostMapping("/updateState")
    @ResponseBody
    @RepeatSubmit
    public AjaxResult updateState(String bid) {
    	
    	Map<String, Object> params = new HashMap<String, Object>();
        params.put("moduleTable", moduleTable);
        AjaxResult ajaxResult = new AjaxResult();
        try {
            ajaxResult = deliveryRequestService.updateState(bid);
        } catch (Exception e) {
        	e.printStackTrace();
            ajaxResult = AjaxResult.error(this.getExceptionMessage(e));
        }
        return ajaxResult;
    }


    /**
     * @Description: 删除未审核数据
     * @Param: [params]
     * @return: com.dhecp.common.core.domain.AjaxResult
     * @Author: hlf
     * @date: 2022-08-17 14:55
     */
    @RequiresPermissions("storage:deliveryRequest:delete")
    @Log(title = "删除海外仓发货申请", businessType = BusinessType.UPDATE)
    @PostMapping("/delete")
    @ResponseBody
    @RepeatSubmit
    public AjaxResult delete(@RequestParam Map<String, Object> params) {
        params.put("moduleTable", moduleTable);
        AjaxResult ajaxResult = new AjaxResult();
        try {
            ajaxResult = deliveryRequestService.delete(params);
        } catch (Exception e) {
            ajaxResult = AjaxResult.error(this.getExceptionMessage(e));
        }
        return ajaxResult;
    }



    /**
     * 打开流转页
     * @return
     * @author DH-Xxj
     */
    @RequiresPermissions("storage:deliveryRequest:flow")
    @PostMapping("/flowpage")
    @ResponseBody
    public AjaxResult flowPage(@RequestParam Map<String, Object> params){
        params.put("moduleTable", moduleTable);
        params.put("prefix", prefix);
        return openFlowPage(params);
    }

    /**
     *@Description: 流转
     *@Param: [params] infoMap 必要参数：非网格字段（包括头部、底部所有显示和隐藏的字段）
     *@Param: [params] infoItems 必要参数：对应实体类的json格式字符串（仅需 guid）
     *@return: com.dhecp.common.core.domain.AjaxResult
     *@Author: hlf
     *@date: 2022-05-09 11:42
     */
    @RequiresPermissions("storage:deliveryRequest:flow")
    @Log(title = "海外仓发货申请", businessType = BusinessType.FLOWGO)
    @PostMapping("/flowgopost")
    @ResponseBody
    @RepeatSubmit
    public AjaxResult flowGoSave(@RequestParam Map<String, Object> params){
        params.put("moduleTable", moduleTable);
        AjaxResult ajaxResult = new AjaxResult();
        try {
            ajaxResult= deliveryRequestService.updateFlowGo(params);
        }catch (Exception e) {
            ajaxResult = AjaxResult.error(this.getExceptionMessage(e));
        }
        return ajaxResult;
    }

    /**
     *@Description: 退回
     *@Param: [params] infoMap 必要参数：非网格字段（包括头部、底部所有显示和隐藏的字段）
     *@Param: [params] 必要参数：对应实体类的json格式字符串（仅需 guid）
     *@return: com.dhecp.common.core.domain.AjaxResult
     *@Author: hlf
     *@date: 2022-05-09 11:42
     */
    @RequiresPermissions("storage:deliveryRequest:flow")
    @Log(title = "海外仓发货申请", businessType = BusinessType.FLOWBACK)
    @PostMapping("/flowbackpost")
    @ResponseBody
    @RepeatSubmit
    public AjaxResult flowBackSave(@RequestParam Map<String, Object> params){
        params.put("moduleTable", moduleTable);
        AjaxResult ajaxResult = new AjaxResult();
        try {
            ajaxResult= deliveryRequestService.updateFlowBack(params);
        }catch (Exception e) {
            ajaxResult = AjaxResult.error(this.getExceptionMessage(e));
        }
        return ajaxResult;
    }

    /**
     * 导出
     */
    @RequiresPermissions("storage:deliveryRequest:export")
    @Log(title = "海外仓发货申请数据导出", businessType = BusinessType.EXPORT)
    @GetMapping("/export")
    @ResponseBody
    @RepeatSubmit
    public AjaxResult export(@RequestParam Map<String, Object> params) throws Exception {
        params.put("moduleTable", moduleTable);
        params.put("entity", new DeliveryRequest());

        List<DeliveryRequest> list = deliveryRequestService.queryList(params);

        params.put("getFieldAttributesType", "export");
        List<SysDictionaryForExport> fieldList = sysDictionaryForFieldService.queryExportFieldList(params);
        ExportExcelUtils<DeliveryRequest> util = new ExportExcelUtils<DeliveryRequest>(moduleTable, new DeliveryRequest());
        return util.exportExcel(list, fieldList, "海外仓发货申请数据", "export");
    }


}